package com.cleaningcloud.auth.service;

import java.util.Objects;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import com.cleaningcloud.common.redis.service.RedisService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


/**
 * 阿里云短信配置
 *
 * @author: Strive
 * @date: 2023/4/16 16:38
 */
@Slf4j
@Data
@Service
@ConfigurationProperties("aliyun.sms")
public class AliyunSmsService {

    private String smsAccessKeyId;
    private String smsAccessKeySecret;
    private String smsEndpoint;
    private String smsSignName;
    private String smsTemplateCode;

    @Autowired
    public RedisService redisService;

    /**
     * 使用 AK&ASK 初始化账号 Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception 短信推送异常
     */
    public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint)
            throws Exception {
        Config config =
                new Config()
                        // 必填，您的 AccessKey ID
                        .setAccessKeyId(accessKeyId)
                        // 必填，您的 AccessKey Secret
                        .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = endpoint;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送短信验证码
     *
     * @param phone 电话号码
     * @throws Exception 短信推送异常
     */
    public boolean sendCode(String phone, String code) throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS
        Client client = createClient(this.smsAccessKeyId, this.smsAccessKeySecret, this.smsEndpoint);
        SendSmsRequest sendSmsRequest =
                new SendSmsRequest()
                        .setSignName(this.smsSignName)
                        .setTemplateCode(this.smsTemplateCode)
                        .setPhoneNumbers(phone)
                        .setTemplateParam("{\"code\":\"" + code + "\"}");
        try {
            log.info("发送短信入参: " + JSONObject.toJSONString(sendSmsRequest));
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            log.info("发送短信结果: " + JSONObject.toJSONString(sendSmsRequest));
            if (Objects.nonNull(sendSmsResponse) && sendSmsResponse.getBody().code.equals("OK")) {
                redisService.setCacheObject(phone, code, 5L, TimeUnit.MINUTES);
                return Boolean.TRUE;
            }
        } catch (TeaException error) {
            // 如有需要，请打印 error
            log.error("短信推送异常结果: " + error.message);
            return Boolean.FALSE;
        } catch (Exception e) {
            TeaException error = new TeaException(e.getMessage(), e);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            log.error("短信推送异常结果: " + error.message);
            return Boolean.FALSE;
        }

        return Boolean.FALSE;
    }
}
